﻿Public Class _Mapping
    Inherits System.Web.UI.Page

    Public Class ModalMessage
        Public Property MessageText As String
        Public Property MessageType As enmMessageType
    End Class

    Public Enum enmMessageType
        Success = 0
        Info = 1
        [Error] = 2
        Attention = 3
    End Enum


    Protected WithEvents ChkFiltra As Global.System.Web.UI.ICheckBoxControl
    Private mCurrentKey As String


    Public Function GetIconaVisibile(ByVal pTipo As Object, ByVal pConfronta As enmMessageType) As Boolean

        If DirectCast(pTipo, enmMessageType) = pConfronta Then
            Return True
        Else
            Return False
        End If

    End Function

    Private Sub gvMap_SelectedIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSelectEventArgs) Handles gvMap.SelectedIndexChanging
        gvMap.SelectedIndex = e.NewSelectedIndex
        Me.lblTipoMapping.Text = "Selezionato :" & gvMap.SelectedDataKey.Value.ToString + " : " + gvMap.SelectedRow.Cells(4).Text

        Me.MyAccordion.SelectedIndex = 1

        Dim lmap As New clsMap()
        lmap.Inizializza(DirectCast(gvMap.SelectedDataKey.Value, Integer))
        'a questo punto devo formattare la griglia
        Me.LV_Mapping.Columns(5).Visible = False

        Context.Session("type_mapping") = gvMap.SelectedDataKey.Value
        Context.Session("mapping") = lmap


        'Me.LV_Mapping.
        LV_Mapping.DataSourceID = ""
        LV_Mapping.DataSource = Nothing
        Context.Session("DS_mapping") = Nothing
        Session.Contents("lvfiltrids") = Nothing
        LV_Mapping.EditIndex = -1
        Session.Contents("NewMapping") = "0"

        LV_filtri.DataSource = Nothing
        lblElencoFiltri.Text = ""
        lblMappingEstraibiliCount.Text = ""

        LV_Mapping.DataBind()
        LV_filtri.DataBind()
        'Me.LV_Mapping.Columns(1).HeaderText = ""
        'TODO Mettere questo nel bottone di ricerca.


    End Sub

    Private Sub AggiungiFiltri(ByVal pDim As String, ByVal pTipo As Integer)

        'pTipo 0 = aggiunta filtri 
        'ptipo  1 = aggiunta source (source normali oppure elemento ALL)
        'ptipo 2 = nuovo target

        Dim lMap As clsMap = DirectCast(Context.Session("mapping"), clsMap)
        Dim ltm As Integer = -1

        Context.Session("TipoSelezione") = pTipo
        Context.Session("Dimensione") = pDim

        If IsNumeric(Context.Session("type_mapping")) Then
            ltm = DirectCast(Context.Session("type_mapping"), Integer)
        End If

        Me.lblALLNO.Visible = False
        Me.btnElementoAll.Visible = False

        If ltm >= 0 Then

            lv_cerca.DataSource = Nothing
            lv_cerca.DataBind()

            cmbDimensioni.DataSource = lMap.getDSDimensioni(ltm)
            cmbDimensioni.DataBind()

            Select Case pTipo
                Case 0
                    lblCapionModal.Text = "Seleziona Filtri"
                    cmbDimensioni.Visible = True
                    lblDimensione.Visible = True
                    LV_Mapping.DataSource = Nothing
                    Context.Session("DS_mapping") = Nothing
                    Me.btnClose.Visible = True
                    Me.btnSeleziona.Visible = True

                Case 1
                    cmbDimensioni.SelectedValue = "_Source_" + pDim
                    cmbDimensioni.Visible = False
                    lblDimensione.Visible = False
                    Me.btnClose.Visible = True
                    Me.btnSeleziona.Visible = True
                    lblCapionModal.Text = "Source : " + pDim
                    'devo verificare che non ci sono elementi ALL in griglia


                    Dim myMapping As clsMap = DirectCast(Context.Session("mapping"), clsMap)
                    Dim lclssource As clsSource = Nothing

                    'cerco il source
                    For Each lclssource In myMapping.ElencoSource
                        If lclssource.Prefix = pDim Then

                            Exit For
                        End If
                    Next

                    'mi restituisce la collezione dell'elemento ALL
                    Dim lcollTot As collElencoSourcerOW = DirectCast(Context.Session("DS_SOURCE_" + lclssource.Num), collElencoSourcerOW)
                    If Not lcollTot Is Nothing AndAlso lcollTot.Count > 0 Then
                        btnElementoAll.Visible = True
                        For Each ls As clsSourceRow In lcollTot
                            If ls.Stato <> 1 Then
                                lblALLNO.Visible = True
                                btnElementoAll.Visible = False
                            Else
                                Exit For
                            End If
                        Next
                    Else
                        btnElementoAll.Visible = True
                    End If

                Case 2
                    cmbDimensioni.SelectedValue = "_Target_" + lMap.PrefixTarget
                    cmbDimensioni.Visible = False
                    lblDimensione.Visible = False
                    Me.btnClose.Visible = False
                    Me.btnSeleziona.Visible = False
                    lblCapionModal.Text = "Target : " + lMap.PrefixTarget

            End Select

            'btnClose.Visible = False
            'btnSave.Visible = False
            'UpdPnlPopupCerca.Update()
            Me.mdlPopup.Show()
        End If



    End Sub


    Protected Sub btnAddFiltri_New_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddFiltri_New.Click

        Session.Contents("NewMapping") = "0"
        LV_Mapping.EditIndex = -1

        Session.Contents("lvfiltrids") = Nothing
        AggiungiFiltri("", 0)

    End Sub

    Protected Sub btnAddFiltri_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddFiltri.Click

        Session.Contents("NewMapping") = "0"
        LV_Mapping.EditIndex = -1
        AggiungiFiltri("", 0)

    End Sub

    Private Sub btnClose_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClose.Click
        'il bottone cancel dalla ricerca dei filtri

        lv_cerca.DataSource = Nothing
        lv_cerca.DataBind()
        txtcerca.Text = ""

        Me.mdlPopup.Hide()

    End Sub

    Protected Sub btnCerca_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnCerca.Click
        'cerca nella dimenssione per poi successivamente impostare dei filtri

        Dim lscerca As String = Me.txtcerca.Text
        Dim ltm As Integer = -1

        If LV_Mapping.EditIndex = 0 Then

        End If

        If IsNumeric(Context.Session("type_mapping")) Then
            ltm = DirectCast(Context.Session("type_mapping"), Integer)
        End If

        If ltm < 0 Or cmbDimensioni.SelectedIndex < 0 Then
            Exit Sub
        End If

        'devo costruire la query di ricerca
        Dim myMapping As clsMap = DirectCast(Context.Session("mapping"), clsMap)


        'cerco su quale dimensione si è deciso di fare la ricerca
        Dim lRicercaSource As clsSource = Nothing
        For Each lSource As clsSource In myMapping.ElencoSource
            If lSource.Prefix = cmbDimensioni.SelectedItem.Text Then
                lRicercaSource = lSource
            End If
        Next

        Dim lsNewMapping As String = Session.Contents("NewMapping").ToString

        If lRicercaSource Is Nothing Then
            'todo qualche problema
            Me.lv_cerca.DataSource = myMapping.GetDsElencoTarget(lscerca, lsNewMapping)
        Else
            Me.lv_cerca.DataSource = lRicercaSource.GetDsElencoSource(lscerca, lsNewMapping)
        End If

        Me.lv_cerca.DataBind()

    End Sub

    Private Sub AggiungiFiltriInGriglia()

        Dim lc As System.Web.UI.WebControls.CheckBox = Nothing
        Dim lcod As String = ""

        Dim lcollTot As collElencoFiltri = DirectCast(Session.Contents("lvfiltrids"), collElencoFiltri)


        'tolgo i filtri su id e ricerca libera 
        Me.txtRicercaLibera.Text = ""
        Me.txtID.Text = ""


        If lcollTot Is Nothing Then
            lcollTot = New collElencoFiltri
        End If

        For Each r As GridViewRow In Me.lv_cerca.Rows
            lc = DirectCast(r.FindControl("chkfiltra"), CheckBox)
            If lc.Checked Then
                mCurrentKey = r.Cells(1).Text
                'r.DataIte()
                If Not lcollTot.Exists(AddressOf MatchClsFiltro) Then
                    Dim f As New clsFiltro
                    f.Prefix = cmbDimensioni.SelectedItem.Text
                    f.Mem_ID = CStr(lv_cerca.DataKeys(r.RowIndex).Value)
                    f.mem_Desc = r.Cells(2).Text
                    f.Mem_Code = ""
                    f.Caricato = False
                    f.IsTarget = cmbDimensioni.SelectedItem.Value.StartsWith("_Target_")
                    lcollTot.Add(f)
                End If

            End If

        Next
        Dim lsl As String = ""
        lv_cerca.DataSource = Nothing
        lv_cerca.DataBind()

        txtcerca.Text = ""


        For Each lf As clsFiltro In lcollTot
            lsl = lsl + "  (" + lf.mem_Desc + ")  "
        Next
        If Len(lsl) > 100 Then
            lblElencoFiltri.Text = Left(lsl, 100) + "..."
        Else
            lblElencoFiltri.Text = lsl
        End If

        'Session.Contents("lvfiltrids") = lcollTot


        'a questo punto devo verificare la query

        Dim myMapping As clsMap = DirectCast(Context.Session("mapping"), clsMap)

        'If lcollTot.Count > 0 Then

        Session.Contents("lvfiltrids") = lcollTot
        LV_filtri.DataSource = lcollTot
        LV_filtri.DataBind()

        Dim ds As DataSet = myMapping.GetDsCountMapping(lcollTot, "", "")
        lblMappingEstraibiliCount.Text = ds.Tables(0).Rows(0).Item(0).ToString


        'Else
        'Me.LV_filtri.DataSource = Nothing
        'Me.LV_filtri.DataBind()

        'End If

        'lblMappingEstraibiliCount.Text = ds.Tables(0).Rows(0).Item(0).ToString

    End Sub

    Private Sub AggiungiSourceInMap(ByVal pDim As String)

        Dim myMapping As clsMap = DirectCast(Context.Session("mapping"), clsMap)

        Dim lc As System.Web.UI.WebControls.CheckBox = Nothing
        Dim lcod As String = ""
        Dim lclssource As clsSource = Nothing

        For Each lclssource In myMapping.ElencoSource
            If lclssource.Prefix = pDim Then

                Exit For
            End If
        Next

        Dim lcollTot As collElencoSourcerOW = DirectCast(Context.Session("DS_SOURCE_" + lclssource.Num), collElencoSourcerOW)

        If lcollTot Is Nothing Then
            lcollTot = New collElencoSourcerOW
        End If

        For Each r As GridViewRow In Me.lv_cerca.Rows
            lc = DirectCast(r.FindControl("chkfiltra"), CheckBox)
            If lc.Checked Then
                mCurrentKey = r.Cells(1).Text
                'r.DataIte()
                If Not lcollTot.Exists(AddressOf MatchClsSourceRow) Then
                    Dim f As New clsSourceRow
                    f.DESCR_ROW = r.Cells(2).Text
                    f.Stato = 2
                    'f.Id_Mapping =
                    f.StatoOri = 2
                    f.VALUE_SOURCE = CStr(lv_cerca.DataKeys(r.RowIndex).Value)
                    lcollTot.Add(f)
                End If

            End If

        Next

        Context.Session("DS_SOURCE_" + lclssource.Num) = lcollTot

    End Sub

    Private Sub AggiungiElementoALLInMap(ByVal pDim As String)

        Dim myMapping As clsMap = DirectCast(Context.Session("mapping"), clsMap)

        Dim lc As System.Web.UI.WebControls.CheckBox = Nothing
        Dim lcod As String = ""
        Dim lclssource As clsSource = Nothing

        'cerco il source
        For Each lclssource In myMapping.ElencoSource
            If lclssource.Prefix = pDim Then

                Exit For
            End If
        Next

        'mi restituisce la collezione dell'elemento ALL
        Dim lcollTot As collElencoSourcerOW = DirectCast(Context.Session("DS_SOURCE_" + lclssource.Num), collElencoSourcerOW)

        If lcollTot Is Nothing Then
            lcollTot = New collElencoSourcerOW
        End If

        mCurrentKey = "(ALL)"

        If Not lcollTot.Exists(AddressOf MatchClsSourceRow) Then
            Dim f As New clsSourceRow
            f.DESCR_ROW = "(ALL)"
            f.Stato = 2
            f.StatoOri = 2
            f.VALUE_SOURCE = "(ALL)"
            lcollTot.Add(f)
        End If

        Context.Session("DS_SOURCE_" + lclssource.Num) = lcollTot

    End Sub



    Private Sub btnElementoAll_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnElementoAll.Click

        Dim ltipo As Integer
        Dim lDim As String

        ltipo = CInt(Context.Session("TipoSelezione"))
        lDim = CStr(Context.Session("Dimensione"))

        AggiungiElementoALLInMap(lDim)

        Me.mdlPopup.Hide()

    End Sub

    Private Sub btnSeleziona_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSeleziona.Click
        'seleziona dei filtri e da un risultato count sul mapping

        Dim ltipo As Integer
        Dim lDim As String

        ltipo = CInt(Context.Session("TipoSelezione"))
        lDim = CStr(Context.Session("Dimensione"))

        Select Case ltipo
            Case 0
                AggiungiFiltriInGriglia()
            Case 1
                AggiungiSourceInMap(lDim)
            Case 2
                'gestito direttamente nel check
        End Select

        Me.mdlPopup.Hide()

    End Sub


    Private Function MatchClsSourceRow(ByVal p As clsSourceRow) As Boolean

        If p.VALUE_SOURCE.ToString = mCurrentKey Then
            Return True
        Else
            Return False
        End If

    End Function


    Private Function MatchClsFiltro(ByVal p As clsFiltro) As Boolean

        If p.Mem_ID.ToString = mCurrentKey Then
            Return True
        Else
            Return False
        End If

    End Function

    Private Sub LV_filtri_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles LV_filtri.RowCommand

        Select Case e.CommandName

            Case "CancellaFiltro"
                'LV_filtri.DeleteRow(CInt(e.CommandArgument))
                Dim r As Integer
                r = CType(e.CommandArgument, Integer)
                LV_filtri.SelectRow(r)

                Dim lsKey As String = LV_filtri.SelectedValue.ToString
                'Dim ds As ElencoFiltri = DirectCast(LV_filtri.DataSource, ElencoFiltri)
                Dim ds As collElencoFiltri = DirectCast(Session.Contents("lvfiltrids"), collElencoFiltri)
                'Session.Contents("lvfiltrids")
                For Each f As clsFiltro In ds
                    If lsKey = f.Mem_ID.ToString Then
                        ds.Remove(f)
                        Exit For
                    End If
                Next

                LV_filtri.DataSource = Nothing
                LV_filtri.DataSource = ds

                LV_filtri.DataBind()

                'ricalcolo
                Dim myMapping As clsMap = DirectCast(Context.Session("mapping"), clsMap)
                Dim dsCount As DataSet = myMapping.GetDsCountMapping(ds, "", "")
                lblMappingEstraibiliCount.Text = dsCount.Tables(0).Rows(0).Item(0).ToString


        End Select


    End Sub

    Private Sub LV_Mapping_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles LV_Mapping.RowCancelingEdit

    End Sub

    Private Function GetFiltroTargetFromRow(ByVal pr As Integer) As clsFiltro
        'Dim gr As GridViewRow '= DirectCast(e.Row, GridViewRow)
        Return Nothing

    End Function

    Private Sub LV_Mapping_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles LV_Mapping.RowCommand

        'Dim gr As GridViewRow '= DirectCast(e.Row, GridViewRow)
        Dim myMapping As clsMap = DirectCast(Context.Session("mapping"), clsMap)

        Select Case e.CommandName
            Case "Edit"
                'a questo livello devo 
                'salvarmi il contesto della riga
                'LV_Mapping.EditIndex = 0

                Dim i As Integer

                Dim idMapping As String = DirectCast(Me.LV_Mapping.Rows(CInt(e.CommandArgument)).FindControl("id_mappingLabel"), Label).Text
                Context.Session("ID_mapping") = idMapping

                Dim ds As DataSet = myMapping.GetDsMapping(Nothing, "", idMapping)

                Context.Session("DS_mapping") = ds

                LV_Mapping.DataSource = ds

                'qua imposto i datasource di sessione per le colonne
                For i = 1 To myMapping.NumSource
                    Context.Session("DS_SOURCE_" + i.ToString) = myMapping.ElencoSource(i - 1).GetDsElencoSourceRow(CType(LV_Mapping.DataKeys(CType(e.CommandArgument, Integer)).Value, Integer))
                Next


                'inizio reimpostazione datasource mapping
                'questa parte la faccio dopo perchè 
                'non ho in cnna l'id del target
                'ho in cannoa l'id del mapping
                'non ho la query che ricava il ds
                'non so come si comporterebbe
                'quindi l'implementazione sarebbe quella di aggiungere nella collezione dei filtri un elemento id mapping
                'gestirlo nella composizione della query
                'non inserirlo nei filtri in griglia
                'toglierlo quando si esce dall'edi
                'un pò lunghetta

                'LV_Mapping.DataSourceID = ""

                'Dim lcollTot As collElencoFiltri = DirectCast(Session.Contents("lvfiltrids"), collElencoFiltri)

                'Dim f As clsFiltro = GetFiltroTargetFromRow(CType(e.CommandArgument, Integer))

                'If Not f Is Nothing Then

                '    mCurrentFiltro = f.Mem_ID.ToString
                '    'r.DataIte()
                '    If Not lcollTot.Exists(AddressOf MatchClsFiltro) Then
                '        lcollTot.Add(f)
                '    End If


                'End If

                'Dim ds As DataSet = myMapping.GetDsMapping(lcollTot)

                'Context.Session("DS_mapping") = ds


                'LV_Mapping.DataSource = ds
                'fine reimpostazione datasource mapping


                'visualizzare i tasti di cancel e conferma
                LV_Mapping.Columns(giCOL_Cancel).Visible = True
                LV_Mapping.Columns(giCOL_Delete).Visible = False
                LV_Mapping.Columns(giCOL_Edit).Visible = False
                LV_Mapping.Columns(giCOL_Save).Visible = True


            Case "Save"
                'verifico che posso salvare e salvo.
                FillCollFiltriFromNew()


            Case "Cancel"
                'a questo livello devo 
                '


                'visualizzare i tasti di cancel e conferma
                LV_Mapping.Columns(giCOL_Cancel).Visible = False
                LV_Mapping.Columns(giCOL_Delete).Visible = True
                LV_Mapping.Columns(giCOL_Edit).Visible = True
                LV_Mapping.Columns(giCOL_Save).Visible = False
                LV_Mapping.EditIndex = -1
                Session.Contents("NewMapping") = "0"

            Case "Delete"
                'recupero l'id di mapping
                Dim idMapping As String = DirectCast(Me.LV_Mapping.Rows(CInt(e.CommandArgument)).FindControl("id_mappingLabel"), Label).Text
                Context.Session("ID_mapping") = idMapping
                'memorizzo l'operazione di messaggio
                Context.Session("msgbox") = "delete"

                Dim l As New List(Of ModalMessage)

                Dim mm As ModalMessage
                mm = New ModalMessage
                mm.MessageText = "confermi l'eliminazione ?"
                mm.MessageType = enmMessageType.Info

                btnPostCancel.Visible = True
                btnPostOK.Visible = True
                l.Add(mm)

                grvMsg.DataSource = l
                grvMsg.DataBind()
                udpMsj.Update()
                mpeMsg.Show()


            Case "AddColRow"
                'a questo punto l'argomento è la colonna
                'richiamo un pannello modale

                Dim lc As Integer = CInt(Right(e.CommandArgument.ToString, 1))
                Dim lcoll As collElencoSourcerOW = DirectCast(Context.Session("DS_SOURCE_" + lc.ToString), collElencoSourcerOW)
                Dim f As New clsSourceRow

                For Each ls As clsSource In myMapping.ElencoSource
                    If ls.Num = lc.ToString Then
                        'qua ottengo la dimensione
                        AggiungiFiltri(ls.Prefix, 1)
                    End If
                Next

                '
                Debug.WriteLine("")


            Case Else

                If e.CommandName.StartsWith("DelRowCol_") Then
                    'recupero la colonna di source
                    Dim lc As Integer = CInt(Right(e.CommandName, 1))

                    '
                    Dim lcoll As collElencoSourcerOW = DirectCast(Context.Session("DS_SOURCE_" + lc.ToString), collElencoSourcerOW)

                    For Each f As clsSourceRow In lcoll
                        If CStr(e.CommandArgument) = f.VALUE_SOURCE Then
                            If gViewStrike Then
                                If f.Stato = 1 Then
                                    f.Stato = f.StatoOri
                                Else
                                    f.Stato = 1
                                End If
                            Else
                                lcoll.Remove(f)

                            End If
                            Exit For
                        End If
                    Next
                    Context.Session("DS_SOURCE_" + lc.ToString) = lcoll

                    Dim lv As ListView '= DirectCast(e.
                    lv = DirectCast(LV_Mapping.Rows(Me.LV_Mapping.EditIndex).FindControl("SOURCE_1"), ListView)
                    lv.DataSource = lcoll
                    lv.DataSourceID = ""
                    lv.DataBind()

                    'cerco la lv nella rigacorrente

                    'LV_filtri.DataSource = Nothing
                    'LV_filtri.DataSource = ds
                    'DirectCast(DirectCast(e.CommandSource, ListViewDataItem).FindControl("value_sourceLabel"), Label).Font.Strikeout = True
                    'LV_filtri.DataBind()
                End If


        End Select


    End Sub

    Private Sub LV_Mapping_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles LV_Mapping.RowCreated
        Dim gr As GridViewRow = DirectCast(e.Row, GridViewRow)
        Dim myMapping As clsMap = DirectCast(Context.Session("mapping"), clsMap)
        Dim i As Integer
        If gr.RowIndex = -1 Then
            'qua imposto le intestazioni delle colonne
            For i = 1 To myMapping.NumSource
                LV_Mapping.Columns(i + giCOL_1).Visible = True
                LV_Mapping.Columns(i + giCOL_1).HeaderText = myMapping.ElencoSource(i - 1).Prefix
            Next
            For i = myMapping.NumSource + giCOL_1 + 1 To giCOL_N
                LV_Mapping.Columns(i).Visible = False
            Next


        Else
            'qua imposto il datasource
            'test
            Dim lv As ListView
            Dim lid_mapping As Integer
            If Not gr.DataItem Is Nothing Then
                lid_mapping = CType(DirectCast(gr.DataItem, DataRowView).Item(1), Integer)
                For i = 1 To myMapping.NumSource
                    lv = DirectCast(gr.FindControl("SOURCE_" + i.ToString), ListView)
                    lv.DataSourceID = ""
                    lv.DataSource = myMapping.ElencoSource(i - 1).GetDsElencoSourceRow(lid_mapping)
                    'lv.DataBind()
                Next
                'sbianco le colonne in più
                For i = myMapping.NumSource To giCOL_N - giCOL_1
                    lv = DirectCast(gr.FindControl("SOURCE_" + i.ToString), ListView)
                    lv.DataSourceID = ""
                Next

            End If

        End If



    End Sub

    Private Sub LV_Mapping_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles LV_Mapping.RowDeleting

    End Sub

    Private Sub LV_Mapping_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles LV_Mapping.RowEditing

        ''Me.LV_Mapping.DataSourceID = ""
        ''LV_Mapping.DataSource = DirectCast(Context.Session("DS_mapping"), DataSet)

        ''impostare tutti i sql datasource delle colonne della griglia come con quello 1
        ''implementare la funzione che ritorni le query
        ''sull'edit salvare i sql datasource nelle sessioni
        ''ed impostare i sql datasource_e a quel valore
        ''verificare se riesco ad aliminare DA VERIFICARE
        ''per vedere cosa eliminare inserire nei bottoni la seguente strina
        ''                    <td<asp:ImageButton  CommandName="DelRowCol_1" CommandArgument='<%# Eval("VALUE_SOURCE") %>' ImageUrl="~/App_Themes/CancellaRowColMap.gif" runat="server" ID="btnEliminaRowMap_1" /></td>
        ''in questo modo è possibile sfruttura in questo evento il parametro e
        ''        ? e
        ''{System.Web.UI.WebControls.GridViewCommandEventArgs}
        ''    CommandArgument: "34" {String}
        ''    CommandName: "DelRowCol_1"
        ''    CommandSource: {System.Web.UI.WebControls.ListViewDataItem}
        ''    Empty: {System.EventArgs}
        ''    Row: {System.Web.UI.WebControls.GridViewRow}


        ''Me.LV_Mapping.Rows(e.NewEditIndex).FindControl("SOURCE_1")
        ''    {System.Web.UI.WebControls.ListView}
        ''System.Web.UI.WebControls.ListView: {System.Web.UI.WebControls.ListView}
        'Dim lsqlds As System.Web.UI.WebControls.ListView
        'lsqlds = DirectCast(Me.LV_Mapping.Rows(e.NewEditIndex).FindControl("SOURCE_1"), System.Web.UI.WebControls.ListView)
        ''lsqlds.Items.Remove()
        ''lsqlds.Items.Insert()

        'Dim lds As SqlDataSource
        'lds = DirectCast(Me.LV_Mapping.Rows(e.NewEditIndex).FindControl("SqlDs_SOURCE_1"), SqlDataSource)

        '' lsqlds.Items.Remove(New ListViewDataItem(0, 0))

        'For Each lr As ListViewDataItem In lsqlds.Items
        '    lsqlds.Items.Remove(lr) 'non funziona
        '    'lsqlds.DataBind()
        '    Exit For
        'Next

        ''lsqlds.DeleteItem(0) NON FUNZIONA SE NON VIENE SPECIFICATO UN DELETECOMMAND SUL SQLDATASOURCE

    End Sub

    Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub



    Private Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
        If Not Page.IsPostBack Then
            Me.LV_Mapping.DataSourceID = ""
        Else
            'Me.LV_Mapping.DataSourceID = "SqlDS_Mapping"
            LV_Mapping.DataSource = DirectCast(Context.Session("DS_mapping"), DataSet)
            LV_Mapping.DataBind()


            'sono in edit ?
            If LV_Mapping.EditIndex <> -1 And LV_Mapping.Rows.Count > 0 Then
                'imoisto i ds della riga
                'Dim lcoll As collElencoSourcerOW = Nothing '= DirectCast(Context.Session("DS_SOURCE_" + lc.ToString), collElencoSourcerOW)
                Dim myMapping As clsMap = DirectCast(Context.Session("mapping"), clsMap)
                Me.LV_Mapping.EditIndex = 0
                Dim gr As GridViewRow = DirectCast(Me.LV_Mapping.Rows(Me.LV_Mapping.EditIndex), GridViewRow)

                For i As Integer = 1 To myMapping.NumSource
                    Dim lv As ListView
                    lv = DirectCast(gr.FindControl("SOURCE_" + i.ToString), ListView)
                    lv.DataSourceID = ""
                    lv.DataSource = DirectCast(Context.Session("DS_SOURCE_" + i.ToString), collElencoSourcerOW)

                    lv.DataBind()
                Next
                'Me.LV_Mapping.EditIndex = 0

            End If

            'Dim ls As String = ""

            'ls = Context.Session("lblCapionModal.Text").ToString
            'lblCapionModal.Text = ls



        End If

    End Sub

    Public Function GetVisibleCheck(ByVal pCheckStato As Integer) As Boolean
        If pCheckStato = 1 Then
            Return True
        Else
            Return False
        End If
    End Function

    Public Function getCssClassSource(ByVal pstato As String) As String
        Return "rowsourcestato_" + pstato.ToString
    End Function

    Public Function get_SqlDS_SOURCE(ByVal n As Integer) As String

        Dim lsql As String
        lsql = "SELECT DESCR_ROW "
        lsql = lsql & " FROM [BBI_MAPPING].[BwAppMap].[v_ElencoRowSourceMap_1]"
        lsql = lsql & " where id_mapping = @id_mapping "
        Return lsql
        Return ""
    End Function


    Private Sub CancelEditing_LV_Mapping()
        LV_Mapping.Columns(giCOL_Cancel).Visible = False
        LV_Mapping.Columns(giCOL_Delete).Visible = True
        LV_Mapping.Columns(giCOL_Edit).Visible = True
        LV_Mapping.Columns(giCOL_Save).Visible = False
        LV_Mapping.EditIndex = -1
        Session.Contents("NewMapping") = "0"

    End Sub
    Private Sub FillMapping()
        CancelEditing_LV_Mapping()

        If IsNumeric(txtID.Text) Then
            Me.lblElencoFiltri.Text = "ID Mapping = " + txtID.Text
        ElseIf txtRicercaLibera.Text <> "" Then
            Me.lblElencoFiltri.Text = "Ricerca Source contenente = " + txtRicercaLibera.Text
        End If



        LV_Mapping.DataSourceID = ""

        Dim myMapping As clsMap = DirectCast(Context.Session("mapping"), clsMap)
        Dim lcollTot As collElencoFiltri = DirectCast(Session.Contents("lvfiltrids"), collElencoFiltri)

        Dim ds As DataSet = myMapping.GetDsMapping(lcollTot, Me.txtRicercaLibera.Text, Me.txtID.Text)

        'Debug.WriteLine DirectCast(LV_Mapping.Columns(3), System.Web.UI.WebControls.TemplateField).ItemTemplate.controls
        'For Each b As DataControlField In LV_Mapping.Columns
        '    Debug.WriteLine("p")
        '    Debug.WriteLine(b.ControlStyle)

        'Next
        'LV_Mapping.DataSource = ds
        'LV_Mapping.DataBind()
        lblMappingEstraibiliCount.Text = ds.Tables(0).Rows.Count.ToString

        Context.Session("DS_mapping") = ds

        LV_Mapping.DataSource = ds

        MyAccordion.SelectedIndex = 2

    End Sub
    Protected Sub btnFillMapping_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnFillMapping.Click

        FillMapping()
        'LV_Mapping.DataBind()
    End Sub

    Private Sub MyAccordion_ItemCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.CommandEventArgs) Handles MyAccordion.ItemCommand

    End Sub

    Private Sub MyAccordion_ItemCreated(ByVal sender As Object, ByVal e As AjaxControlToolkit.AccordionItemEventArgs) Handles MyAccordion.ItemCreated

    End Sub

    Private Sub MyAccordion_ItemDataBound(ByVal sender As Object, ByVal e As AjaxControlToolkit.AccordionItemEventArgs) Handles MyAccordion.ItemDataBound

    End Sub

    Private Sub btnNuovoMapping_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnNuovoMapping.Click

        Session.Contents("NewMapping") = "1"
        lblMappingEstraibiliCount.Text = "0"
        AggiungiFiltri("", 2)

    End Sub
    Protected Friend Sub chkFiltra_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ChkFiltra.CheckedChanged

        Dim ltipo As Integer
        Dim lDim As String

        ltipo = CInt(Context.Session("TipoSelezione"))

        If ltipo <> 2 Then Exit Sub

        lDim = CStr(Context.Session("Dimensione"))

        Dim lch As CheckBox = DirectCast(sender, CheckBox)
        Dim row As GridViewRow = DirectCast(lch.NamingContainer, GridViewRow)

        'a questo punto devo verificare che è un nuovo mapping ?
        'no perchè faccio selezionare solo quelli nuovi
        'e poi comunque nel salva farò un sacco di controlli

        'ora devo ricavarmi il codice e la descrizione

        Dim f As New clsNewTarget
        f.DESCR_ROW = row.Cells(2).Text
        f.VALUE_TARGET = CStr(lv_cerca.DataKeys(row.RowIndex).Value)

        'qua devo preparare il datasource ed andare in edit

        Dim myMapping As clsMap = DirectCast(Context.Session("mapping"), clsMap)

        Dim ds As DataSet = myMapping.GetDsMappingNew(f)
        'Dim ds As DataSet = myMapping.GetDsMapping(f)

        Context.Session("DS_mapping") = ds
        Context.Session("NewTarget") = f

        LV_Mapping.DataSource = ds


        'qua imposto i datasource di sessione per le colonne
        For i As Integer = 1 To myMapping.NumSource
            Context.Session("DS_SOURCE_" + i.ToString) = Nothing
        Next


        'visualizzare i tasti di cancel e conferma
        LV_Mapping.Columns(giCOL_Cancel).Visible = True
        LV_Mapping.Columns(giCOL_Delete).Visible = False
        LV_Mapping.Columns(giCOL_Edit).Visible = False
        LV_Mapping.Columns(giCOL_Save).Visible = True

        LV_Mapping.EditIndex = 0

        Me.mdlPopup.Hide()
        MyAccordion.SelectedIndex = 2

    End Sub

    Private Sub lv_cerca_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles lv_cerca.RowDataBound

        Dim ltipo As Integer

        ltipo = CInt(Context.Session("TipoSelezione"))
        Dim lbAutoPostBack As Boolean

        If ltipo = 2 Then
            lbAutoPostBack = True
        End If

        If e.Row.RowIndex > -1 Then

            Dim lc As CheckBox
            lc = DirectCast(e.Row.FindControl("ChkFiltra"), CheckBox)
            lc.AutoPostBack = lbAutoPostBack

        End If

    End Sub

    Private Sub FillCollFiltriFromNew()
        'questo mi serve per riempire la coll filtri 
        'con la collfiltri sfrutto la query per cercare se ci sono mapping simili
        'questa la sfrutto sia in edit che in new
        'quindi dal datasource della griglia mi ricavo l'id mapping e il taarget
        'e poi leggo tutti i datasource delle colonne source

        Dim lcollFiltri As New collElencoFiltri
        Dim myMapping As clsMap = DirectCast(Context.Session("mapping"), clsMap)

        Dim ds As DataSet = DirectCast(Session("DS_mapping"), DataSet)
        Dim f As clsFiltro
        Dim rMapping As DataRow = ds.Tables(0).Rows(0)
        Dim lId_Mapping As Integer


        'verifico che ci sono tutte le dimensioni
        For i As Integer = 1 To myMapping.NumSource
            Dim lbok As Boolean
            lbok = False

            Dim dss As collElencoSourcerOW = DirectCast(Context.Session("DS_SOURCE_" + i.ToString), collElencoSourcerOW)

            If dss Is Nothing Then
                'impossibile inserire se non è presente niente
            Else
                For Each sr As clsSourceRow In dss
                    If sr.Stato <> 1 Then 'se non è un'elemento eliminato
                        lbok = True
                        Exit For
                    End If

                Next

            End If

            If Not lbok Then
                'impossibile inserire se non è presente niente
                Dim l As New List(Of ModalMessage)
                Context.Session("msgbox") = "Info_delete"

                Dim mm As ModalMessage
                mm = New ModalMessage
                mm.MessageText = "Attenzione inserire elementi per ogni dimensione SOURCE!"
                mm.MessageType = enmMessageType.Error

                btnPostCancel.Visible = False
                btnPostOK.Visible = True
                l.Add(mm)

                grvMsg.DataSource = l
                grvMsg.DataBind()
                udpMsj.Update()
                mpeMsg.Show()

                Exit Sub
            End If
        Next i



        lId_Mapping = CInt(rMapping.Item("ID_MAPPING"))

        f = New clsFiltro
        f.mem_Desc = CStr(rMapping.Item("DESC_TARGET"))
        f.Mem_ID = CStr(rMapping.Item("VALUE_TARGET"))
        f.IsTarget = True
        f.Prefix = myMapping.PrefixTarget

        lcollFiltri.Add(f)



        'qua imposto i datasource di sessione per le colonne
        For i As Integer = 1 To myMapping.NumSource

            Dim dss As collElencoSourcerOW = DirectCast(Context.Session("DS_SOURCE_" + i.ToString), collElencoSourcerOW)

            For Each sr As clsSourceRow In dss
                If sr.Stato <> 1 Then 'se non è un'elemento eliminato
                    f = New clsFiltro
                    f.mem_Desc = sr.DESCR_ROW
                    f.Mem_ID = sr.VALUE_SOURCE
                    f.IsTarget = False
                    f.Prefix = myMapping.getPrefixSource(i)

                    lcollFiltri.Add(f)
                End If

            Next
        Next i
        'a questo punto ho in canna i miei filtri

        Dim dsCheck As DataSet
        dsCheck = Nothing


        'verifica con i filtri e che nel mapping non esiste l'elemento ALL
        dsCheck = myMapping.GetDsMappingCheck(lcollFiltri, lId_Mapping)

        'vedo cosa mi ritorna il dataset anagrafico con l'id del mapping


        If dsCheck.Tables(0).Rows.Count > 0 Then
            'esistono dei mapping identici
            'posso selezionare i source e dargli uno stato = 9 e a quel punto avere uno stile per questi
            'oppure far vedere un oggetto in piu (icona)

            'setto il check sui source
            For i As Integer = 1 To myMapping.NumSource

                Dim dss As collElencoSourcerOW = DirectCast(Context.Session("DS_SOURCE_" + i.ToString), collElencoSourcerOW)

                'dss = myMapping.SetDsSourceRowCheckStato(dss, dsCheck.Tables(0))
                For Each s As clsSourceRow In dss
                    s.CheckStato = 0
                    s.DescrCheck = ""
                    For Each r As DataRow In dsCheck.Tables(0).Rows
                        If CStr(r("SOURCE_" + i.ToString)) = s.VALUE_SOURCE Then

                            s.CheckStato = 1
                            s.DescrCheck = "Trovata corrispondenza in mapping : " + CStr(r("ID_MAPPING"))
                            Exit For
                        End If
                    Next r
                Next s

                Context.Session("DS_SOURCE_" + i.ToString) = dss

            Next i

            MessageBox("Info", "Esistono mapping identici", enmMessageType.Attention, False)

        Else
            'ok posso salvare
            'Debug.WriteLine("salvataggio")
            'la collezione dei filtri è quella che devo salvare come source tranne l'elemento target.
            'non ho bisogno proprio di nient'altro

            If myMapping.SaveMapping(lcollFiltri, lId_Mapping) Then
                'salvataggio corretto

                ds = Nothing
                ds = myMapping.GetDsMapping(Nothing, Me.txtRicercaLibera.Text, lId_Mapping.ToString)

                Context.Session("DS_mapping") = ds

                LV_Mapping.DataSource = ds
                LV_Mapping.EditIndex = -1
                Session.Contents("NewMapping") = "0"
                LV_Mapping.Columns(giCOL_Cancel).Visible = False
                LV_Mapping.Columns(giCOL_Delete).Visible = True
                LV_Mapping.Columns(giCOL_Edit).Visible = True
                LV_Mapping.Columns(giCOL_Save).Visible = False
                MessageBox("Info", "Salvataggio mapping eseguito", enmMessageType.Success, False)

            Else
                'errori nel salvataggio
                MessageBox("Info", "Operazione annullata", enmMessageType.Error, False)
            End If

        End If


    End Sub



    Private Sub btnPostOK_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPostOK.Click

        Dim lspost As String = CStr(Context.Session("msgbox"))
        Dim myMapping As clsMap = DirectCast(Context.Session("mapping"), clsMap)


        Dim l As New List(Of ModalMessage)
        Context.Session("msgbox") = "Info_delete"

        Select Case lspost
            Case "delete"
                '
                Dim mm As ModalMessage

                Dim lidmapping As Integer = CInt(Context.Session("id_mapping"))
                If myMapping.DeleteMapping(lidmapping) Then
                    Dim ri As Integer = -1
                    Dim lr As Label = Nothing
                    For Each r As GridViewRow In LV_Mapping.Rows

                        lr = DirectCast(r.FindControl("id_mappingLabel"), Label)
                        If lr.Text = lidmapping.ToString Then
                            r.Visible = False
                            r.Height = 0
                            ri = r.RowIndex
                            'r.RowType
                            'r.BackColor = Drawing.Color.Black
                            Exit For
                        End If

                    Next

                    'LV_Mapping.DeleteRow(ri)
                    'LV_Mapping.ac()
                    mm = New ModalMessage
                    mm.MessageText = "Mapping eliminato"
                    mm.MessageType = enmMessageType.Info

                    FillMapping()




                Else

                    mm = New ModalMessage
                    mm.MessageText = "Operazione annullata"
                    mm.MessageType = enmMessageType.Error



                End If

                btnPostCancel.Visible = False
                btnPostOK.Visible = True
                l.Add(mm)

                grvMsg.DataSource = l
                grvMsg.DataBind()
                udpMsj.Update()
                'mpeMsg.Show()
                'updpnlacc.UpdateMode = UpdatePanelUpdateMode.Conditional
                'updpnlacc.Update()
                'updpnlacc.UpdateMode = UpdatePanelUpdateMode.Always

                'LV_Mapping

        End Select

    End Sub

    Private Sub btnPostCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPostCancel.Click

    End Sub

    Protected Sub grvMsg_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles grvMsg.SelectedIndexChanged

    End Sub


    Private Sub MessageBox(ByVal pSession As String, ByVal pMessaggio As String, ByVal pType As enmMessageType, ByVal pCancelVisible As Boolean)

        Dim l As New List(Of ModalMessage)
        Context.Session("msgbox") = pSession

        Dim mm As ModalMessage
        mm = New ModalMessage
        mm.MessageText = pMessaggio
        mm.MessageType = pType

        btnPostCancel.Visible = pCancelVisible
        btnPostOK.Visible = True
        l.Add(mm)

        grvMsg.DataSource = l
        grvMsg.DataBind()
        udpMsj.Update()
        mpeMsg.Show()

    End Sub

End Class